import { MiddlewareConsumer, Module } from '@nestjs/common';
import { MulterModule } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname, join } from 'path';
import { UploadController } from './upload.controller';
import { UploadService } from './upload.service';
import { MinioMiddleware } from '../middleware/minio.middleware';
import { ConfigService } from '@nestjs/config';
import { ConfigEnum } from '../enum/config.enum';

@Module({
  imports: [
    MulterModule.registerAsync({
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        storage: diskStorage({
          destination: join(
            __dirname,
            '../../../',
            configService.get<string>(ConfigEnum['FILE_UPLOADS_DIR']) ||
              'uploads',
          ),

          filename: (req, file, cb) => {
            const ext = extname(file.originalname);
            const uniqueSuffix =
              Date.now() + '-' + Math.round(Math.random() * 1e9);
            cb(null, file.fieldname + '-' + uniqueSuffix + ext);
          },
        }),
      }),
    }),
  ],
  controllers: [UploadController],
  providers: [UploadService],
})
export class UploadModule {
  configure(consumer: MiddlewareConsumer) {
    // 任何地方，使用Minio中间件
    consumer.apply(MinioMiddleware).forRoutes('files/minio');
  }
}
